import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getxdemo/get/get_extension.dart';
import 'package:getxdemo/http/http_request.dart';
import 'package:getxdemo/http/request_api.dart';
import 'package:getxdemo/http/request_result.dart';
import 'package:getxdemo/utils/toast_util.dart';

class Request {
  static void get(
    String url,
    params, {
    bool isJson = false,
    bool loading = true,
    Success? success,
    Fail? fail,
  }) {
    _request(Method.GET, url, params,
        isJson: isJson, loading: loading, success: success, fail: fail);
  }

  static void post(
      String url,
      params, {
        bool isJson = false,
        bool loading = true,
        Success? success,
        Fail? fail,
      }) {
    _request(Method.POST, url, params,
        isJson: isJson, loading: loading, success: success, fail: fail);
  }


  static void _request<T>(
    Method method,
    String url,
    params, {
    bool isJson = false,
    bool loading = true,
    Success? success,
    Fail? fail,
  }) {
    if (loading) {
      Get.showLoading();
    }
    debugPrint("request url ==============> ${RequestApi.baseurl}$url");
    params.forEach((key, value) {
      if (url.contains(key)) {
        url = url.replaceAll(":$key", value.toString());
      }
    });
    HttpRequest.request(method, url, params, isJson: isJson ,success: (result) {
      if (success != null) {
        Result resultModel = Result.fromJson(result);
        debugPrint("request success =>$resultModel");
        if (resultModel.errorCode == 0) {
          success(resultModel.data);
        } else {
          if (loading) {
            Get.dismissDialog();
          }
          if(fail != null){
            fail(resultModel.errorCode,resultModel.errorMsg);
          }
        }
      }
    }, fail: (code, msg) {
      if (loading) {
        Get.dismissDialog();
      }
      if (fail != null) {
        fail(code, msg);
      }
      ToastUtils.show(msg);
    });
  }
}
